package com.github.niefy.modules.openapi.resource.controller;

import cn.hutool.core.bean.BeanUtil;
import com.github.niefy.common.utils.R;
import com.github.niefy.modules.openapi.resource.dto.in.TemplateMsgOpen_001;
import com.github.niefy.modules.wx.service.TemplateMsgService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * openapi-模板消息
 */
@RestController
@RequestMapping("/openapi/api")
@Tag(name = "openapi资源接口-模板消息")
@RequiredArgsConstructor
@Slf4j
public class TemplateMsgOpenController {

    private final WxMpService wxMpService;
    private final TemplateMsgService templateMsgService;

    /**
     * 批量代发送模板消息
     */
    @PostMapping("/templateMsg")
    @Operation(summary = "批量代发送模板消息",description = "为第三方应用提供向微信用户发送模板消息的能力，对应的公众号需要提前约定配置")
    public R getStableToken(HttpServletRequest request, HttpServletResponse response,
                            @RequestAttribute String wxAppid,
                            @RequestBody @Validated TemplateMsgOpen_001 in) throws WxErrorException {
        List<WxMpTemplateMessage> msgList = new ArrayList<>();
        in.getMsgList().forEach(msgInfo->{
            var wxMpTemplateMessage = BeanUtil.copyProperties(msgInfo, WxMpTemplateMessage.class);
            msgList.add(wxMpTemplateMessage);
        });
        templateMsgService.sendMsgBatchSpec(msgList, wxAppid);
        return R.ok();
    }
}
